package com.qys.livesMall.open.controller.app;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.kafka.entity.CallBackExpressVO;
import com.qys.livesMall.kafka.entity.ExpressInquiryVO;
import com.qys.livesMall.kafka.send.KafkaClient;
import com.qys.livesMall.open.modal.dto.mail.ExpressInquiryDTO;
import com.qys.livesMall.open.modal.dto.mail.MonitorSubscriptionDTO;
import com.qys.livesMall.open.service.ExpressInquiryService;
import com.qys.livesMall.open.utils.KdApiUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yxh
 */
@RestController
@RequestMapping("/app/express")
@Slf4j
@Tag(name = "快递查询")
public class ExpressInquiryController {

    /**
     * 快递查询缓存key
     */
    public static final String EXPRESS_CHECK = "expressCheck:";

    @Resource
    private ExpressInquiryService expressInquiryService;
    @Resource
    private KafkaClient kafkaClient;
    @Resource
    private RedisCache redisCache;



    /**
     * 快递查询接口
     * @param dto ExpressInquiryDTO
     * @return    ExpressInquiryVO
     */
    @PostMapping("/inquiry")
    @Operation(summary = "快递查询")
    public R<ExpressInquiryVO> expressInquiry(@RequestBody ExpressInquiryDTO dto){
        return R.ok(expressInquiryService.expressTrackQuery(dto));
    }

    /**
     * 在途监控订阅（国际）
     */
    @PostMapping("/monitorSubscription")
    @Operation(summary = "在途监控订阅（国际）")
    public R<?> monitorSubscription(@RequestBody MonitorSubscriptionDTO dto){
        try {
            expressInquiryService.monitorSubscription(dto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 在途监控回调接口
     */
    @PostMapping("/expressTrack")
    @Operation(summary = "在途监控回调接口")
    public Map<String, Object> expressTrack(@RequestParam Map<String, Object> params) {

        boolean ok = false;
        try {
            String decode = URLDecoder.decode((String)params.get("RequestData"), "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(decode);
            String data = JSONObject.toJSONString(jsonObject.get("Data"));
            List<CallBackExpressVO> express = JSON.parseArray(data, CallBackExpressVO.class);
            if(!CollectionUtils.isEmpty(express)){
                kafkaClient.expressMessage(express);
            }
            ok = true;
        } catch (Exception e) {
            log.info("expressTrack send to kafka error:{}",e.getMessage());
        }

        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("EBusinessID", KdApiUtil.EBusinessID);
        resultMap.put("UpdateTime", LocalDateTime.now().toString());
        resultMap.put("Success", ok);
        return resultMap;
    }



    @GetMapping("/inquireCourierCompany/{trackNumber}")
    @Operation(summary = "快递公司查询")
    public R<String> inquireCourierCompany(@PathVariable String trackNumber) {
        String info = redisCache.getCacheObject(EXPRESS_CHECK + trackNumber);
        if(StringUtils.isNotEmpty(info)){
            return R.ok(info);
        }
        String company = KdApiUtil.inquireCourierCompany(trackNumber);
        if(StringUtils.isNotEmpty(company)){
            redisCache.setCacheObject(EXPRESS_CHECK + trackNumber, company, 10L, TimeUnit.DAYS);
        } else {
            company = "null";
            redisCache.setCacheObject(EXPRESS_CHECK + trackNumber, company, 1L, TimeUnit.HOURS);
        }
        return R.ok(company);
    }
}
